# 统一返回
import _thread
import uhashlib
import ubinascii
import json
import time

import uping
import zz_log

config_file_path = "config.json"
config = ""


def ping(ip):
    """
    ping ip 通返回True
    :param ip:
    :return:
    """
    print(f"ping {ip}")
    pinger = uping.Ping(ip, TIMEOUT=1000)
    # Some awesome code
    try:
        pinger.ping()
        return True
    except Exception as ex:
        print(ex)
    return False


def sha256(s):
    if isinstance(s, bytes):
        s = s.decode("utf8")

    hash = uhashlib.sha256(s)
    hash_byte = ubinascii.hexlify(hash.digest())
    # 二进制转字符串
    return hash_byte.decode('UTF-8').strip()


# 返回当前时间字符串 例：2024-06-18 15:15:48
# 传入 machine.RTC().datetime()
def time_to_string(timestamp):
    return '{0:04d}-{1:02d}-{2:02d} {4:02d}:{5:02d}:{6:02d}'.format(*timestamp)


# 当前时间戳（秒）
def time_diff_ms(begin_ns, end_ns):
    return int((begin_ns - end_ns) / 1000000)


def timestamp():
    return time.mktime(time.localtime()) + 946656000


# 开线程
def thread_func(func, *args):
    _thread.start_new_thread(func, args)


# 获取配置内容
def get_config_txt_to_return():
    global config
    if str_is_empty(config):
        try:
            with open(config_file_path, 'r', encoding='utf-8') as file:
                lines = file.readlines()
                for line in lines:
                    config += line
        except Exception as ex:
            print("读config", ex)
    # print(f"config: {config}")
    return json_to_return(config)


def config_get(k):
    r = get_config_txt_to_return()
    val = r.get_data(k)
    if isinstance(val, str):
        val = val.strip()

    return val


def config_set(k, v):
    global config

    r = get_config_txt_to_return()
    r.set_data(k, v)
    r.data.pop("errcode")
    r.data.pop("errmsg")
    #
    config = r.to_json()
    file = open(config_file_path, "w", encoding="utf-8")
    # 写入数据
    file.write(config)
    # 关闭文件
    file.close()


def str_is_empty(s):
    if s is None:
        return True
    if s == "":
        return True

    return False


# 二进制转字符串
def bytes_to_str(s):
    if isinstance(s, str):
        return s
    return s.decode('UTF-8').strip()


# 字符串转二进制
def str_to_bytes(s):
    return bytes(s, 'UTF-8')


def of_return_action(action, errcode, errmsg=""):
    r = of_return(errcode, errmsg)
    r.set_data("action", action)
    return r


def of_return(errcode, errmsg=""):
    r = Return(errcode, errmsg)
    return r


def json_to_return(json_str):
    r = of_return(0)
    dd = {}
    try:
        dd = json.loads(json_str)
    except Exception as ex:
        errmsg = f"json解析异常：{ex}"
        r.set_errcode(123456)
        r.set_errmsg(errmsg)
        zz_log.of().error(errmsg)

    if isinstance(dd, dict):
        for k, v in dd.items():
            r.set_data(k, v)

    return r


class Return:
    def __init__(self, errcode, errmsg=""):
        self.data = {
            "errcode": errcode,
            "errmsg": errmsg,
        }

    def set_data(self, k, v):
        # if isinstance(v, str):
        #     v = v.decode('utf-8')
        self.data[k] = v

    def get_data(self, k, def_val=None):
        if k not in self.data:
            return def_val
        return self.data[k]

    def get_errcode(self):
        return self.data["errcode"]

    def set_errcode(self, errcode):
        self.data["errcode"] = errcode

    def get_errmsg(self):
        return self.data["errmsg"]

    def set_errmsg(self, errmsg):
        self.data["errmsg"] = errmsg

    def ok(self):
        return self.get_errcode() == 0

    def err(self):
        return not self.ok()

    def to_json(self):
        return json.dumps(self.data)
        # return json.dumps(self.data, ensure_ascii=False)
